<template>
  <s-modal
    title="预览"
    :visible="visible"
    width="800px"
    ok-text="渲染数据"
    :confirm-loading="confirmLoading"
    :closable="!confirmLoading"
    @ok="save()"
    @cancel="
      () => {
        if (!confirmLoading) {
          visible = false
        }
      }
    "
  >
    <s-form ref="form" :value="fakeValue">
      <s-form-item
        label="渲染表单"
        name="formId"
        :rules="[{ whitespace: true, required: true, message: '渲染表单不能为空' }]"
      >
        <s-select
          v-model="fakeValue.formId"
          url="/code/module/list"
          :label-field="'moduleValue.' + config.formConfig.module.labelField"
          value-field="id"
        />
      </s-form-item>
      <json-viewer v-model="renderedData" style="width: 100%; height: 500px" />
    </s-form>
  </s-modal>
</template>

<script>
import JsonViewer from '@/components/JsonViewer/index.vue'
export default {
  name: 'RenderPreview',
  components: { JsonViewer },
  props: {
    config: {
      type: Object,
      default: undefined
    }
  },
  data() {
    return {
      fakeValue: {},
      confirmLoading: false,
      visible: false,
      renderedData: null,
      formValueConfig: {}
    }
  },

  methods: {
    open() {
      this.visible = true
    },
    save() {
      const form = this.$refs.form
      form.validate((values) => {
        this.confirmLoading = true
        this.$api
          .POST(
            '/code/module/obtainFormDataByConfig',
            {
              id: values.formId,
              config: this.config
            },
            { dataType: 'json' }
          )
          .then((res) => {
            this.confirmLoading = false
            this.renderedData = res.data
          })
          .catch(() => {
            this.confirmLoading = false
          })
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
